package com.iwith.dongmoon.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TabHost;

import com.google.gson.Gson;
import com.iwith.dongmoon.gsonlist.BizList;
import com.iwith.dongmoon.gsonlist.MemberList;
import com.iwith.dongmoon.util.ApiCode;
import com.iwith.dongmoon.util.ImageDownloader;
import com.iwith.dongmoon.util.ImageDownloader.Mode;
import com.iwith.dongmoon.util.RequestData;
import com.iwith.dongmoon.util.RequestGson;
import com.iwith.dongmoon.util.ResultCode;
import com.iwith.dongmoon.util.SessionManager;
import com.iwith.dongmoon.util.ThreadInterface;
import com.iwith.dongmoon.util.ThreadTask;

public class PersonalInfoModifyActivity extends Activity implements OnClickListener{
	public static final int REQUEST_GALLERY = 1;
	public static final int REQUEST_CAMERA = 0;
	
	private ImageView title;
	
	private RequestGson requestGson = new RequestGson();

	private EditText name;
	private EditText nickname;
	private EditText graduation;
	private EditText email;
	private EditText address;
	private EditText comment;
	private Spinner bizTypeSpinner;
	private EditText bizName;
	private EditText bizPhone;
	private EditText bizAddress;
	private EditText bizInfo;
	
	private Button prevBt;
	private Button personalModifyDoneBt;
	private Button businessModifyDoneBt;

	private Integer [] bizPhotoResource = { R.id.personalinfomodify_bizphoto1, R.id.personalinfomodify_bizphoto2, R.id.personalinfomodify_bizphoto3 }; 
	
	private ImageView [] bizPhoto;
	private ImageView userPhoto;
	
	private ImageDownloader mImageDownloader;;
	
	private TabHost mTabHost;
	private String [] TAB_ID = { ApiCode.USERINFO, ApiCode.BIZINFO };
	private String [] TAB_NAME = { "개인 정보", "업체 정보" };
	private Integer [] TAB_RESOURCE = { R.id.personalinfomodify_personal, R.id.personalinfomodify_job }; 
	
	private String userid;
	private String password;
	private SessionManager mSessionManager=null;
	
	private Context mContext;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personalinfo_modify);
		mSessionManager=new SessionManager(this);
		
		// TODO NOTE : tab setting part
		mTabHost = (TabHost)findViewById(R.id.personalinfomodify_tabhost);
		mTabHost.setup(); // initialize
		
		for(int i=0; i<TAB_ID.length; i++){
			mTabHost.addTab(mTabHost.newTabSpec(TAB_ID[i]).setIndicator(TAB_NAME[i]).setContent(TAB_RESOURCE[i]));
			mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 70;
		}

		mTabHost.setCurrentTab(0);
		Initialize();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		ThreadTask.onFinishAll();
		setPhoto();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		ThreadTask.onFinishAll();
	}
	
	private void Initialize() {
		mContext = this;
		
		userid=mSessionManager.getUserid();
		password=mSessionManager.getPassword();
		
		title = (ImageView) findViewById(R.id.title);
		name = (EditText) findViewById(R.id.personalinfomodify_name);
		nickname = (EditText) findViewById(R.id.personalinfomodify_nickname);
		graduation = (EditText) findViewById(R.id.personalinfomodify_graduation);
		email = (EditText) findViewById(R.id.personalinfomodify_email);
		address = (EditText) findViewById(R.id.personalinfomodify_address);
		comment = (EditText) findViewById(R.id.personalinfomodify_message);
		bizTypeSpinner = (Spinner) findViewById(R.id.personalinfomodify_jobtype);
		bizName = (EditText) findViewById(R.id.personalinfomodify_jobname);
		bizPhone = (EditText) findViewById(R.id.personalinfomodify_jobphone);
		bizAddress = (EditText) findViewById(R.id.personalinfomodify_jobaddress);
		bizInfo = (EditText) findViewById(R.id.personalinfomodify_jobmessage);

		personalModifyDoneBt = (Button) findViewById(R.id.personalinfomodify_personalmodifydonebt);
		businessModifyDoneBt = (Button) findViewById(R.id.personalinfomodify_jobmodifydonebt);
		
		userPhoto = (ImageView)findViewById(R.id.personalinfomodify_userphoto);
		prevBt = (Button)findViewById(R.id.backbtn);
				
		bizPhoto=new ImageView[bizPhotoResource.length];
		for(int i=0; i<bizPhotoResource.length; i++){
			bizPhoto[i]=(ImageView)findViewById(bizPhotoResource[i]);
			bizPhoto[i].setOnClickListener(this);
		}		
		
		mImageDownloader = new ImageDownloader();
		mImageDownloader.setMode(Mode.CORRECT);
		
		setData(ApiCode.USERINFO);

		title.setOnClickListener(this);
		userPhoto.setOnClickListener(this);
		personalModifyDoneBt.setOnClickListener(this);
		businessModifyDoneBt.setOnClickListener(this);
		prevBt.setOnClickListener(this);
	}

	public void modifyInfo(final String code) {
		ThreadInterface threadInterface = new ThreadInterface() {
			MemberList memberList;
			public void onThread() {
				Gson gson = new Gson();
				RequestData data = new RequestData(mContext, ApiCode.API_UPDATEUSERINFORMATION, "POST", "");
				data.addParameter("userid", userid);
				data.addParameter("password", password);
				data.addParameter("username", name.getText().toString());
				data.addParameter("nickname", nickname.getText().toString());
				data.addParameter("email", email.getText().toString());
				data.addParameter("graduation", graduation.getText().toString());
				data.addParameter("address", address.getText().toString());
				data.addParameter("comment", comment.getText().toString());
				data.addParameter("bizName", bizName.getText().toString());
				data.addParameter("bizAddress", bizAddress.getText().toString());
				data.addParameter("bizPhone", bizPhone.getText().toString());
				data.addParameter("bizInfo", bizInfo.getText().toString());
				data.addParameter("bizType", bizTypeSpinner.getSelectedItem().toString());
				
				String sresult = data.getDataPost();
				memberList = gson.fromJson(sresult, MemberList.class);
			}
			public void onThreadEnd() {
				// TODO Auto-generated method stub
				if (memberList.getResultCode().equals(ResultCode.SUCCESS) == false) {
					requestGson.alertToast(mContext, code+" 수정 실패");
					return;
				} else {
					finish();
				}
			}
		};
		ThreadTask task = new ThreadTask((Activity)mContext, threadInterface);
		task.execute();		
	}
	
	private void setPhoto(){
		ThreadInterface threadInterface = new ThreadInterface() {
			MemberList memberList;

			public void onThread() {
				// TODO Auto-generated method stub
				memberList = requestGson.getMemberGsonBySendingAPI(mContext, ApiCode.API_USER, "GET","/"+userid);
			}

			public void onThreadEnd() {
				// TODO Auto-generated method stub
				if (memberList.getResultCode().equals(ResultCode.SUCCESS) == true) {
					String[] bizThumnails = new String[3];
					bizThumnails[0] = memberList.getContent().getBizThumbnail1();
					bizThumnails[1] = memberList.getContent().getBizThumbnail2();
					bizThumnails[2] = memberList.getContent().getBizThumbnail3();

					for (int i = 0; i < 3; i++) {
						if (bizThumnails[i] != null) {
							mImageDownloader.download(bizThumnails[i], bizPhoto[i]);
						}
					}
					
					if(memberList.getContent().getThumbnail()!=null){
						mImageDownloader.download(memberList.getContent().getThumbnail(), userPhoto);
					}
				} else {
					requestGson.alertToast(mContext, "사진 데이터 로딩 실패");
				}
			}
		};
		
		ThreadTask task = new ThreadTask((Activity)mContext, threadInterface);
		task.execute();
	}
	
	private void setData(final String code){
		ThreadInterface threadInterface = new ThreadInterface() {
			MemberList memberList;
			BizList bizList;

			public void onThread() {
				memberList = requestGson.getMemberGsonBySendingAPI(mContext, ApiCode.API_USER, "GET","/"+userid);
				bizList = requestGson.getBizGsonBySendingAPI(mContext, ApiCode.API_BIZTYPE, "GET", "");
			}

			public void onThreadEnd() {
				if (memberList.getResultCode().equals(ResultCode.SUCCESS) == true) {
					name.setText(memberList.getContent().getUsername());
					graduation.setText(memberList.getContent().getGraduation().toString());
					nickname.setText(memberList.getContent().getNickname());
					email.setText(memberList.getContent().getEmail());
					address.setText(memberList.getContent().getAddress());
					comment.setText(memberList.getContent().getComment());
					bizName.setText(memberList.getContent().getBizName());
					bizPhone.setText(memberList.getContent().getBizPhone());
					bizAddress.setText(memberList.getContent().getBizAddress());
					bizInfo.setText(memberList.getContent().getBizInfo());
				} else {
					requestGson.alertToast(mContext, code +" 데이터 로딩 실패");
				}
				
				if(bizList.getResultCode().equals(ResultCode.SUCCESS)==true){
					ArrayList<String> spinnerList = new ArrayList<String>();

					for (int i = 0; i < bizList.getItemCount(); i++) {
						spinnerList.add(bizList.getList().get(i).getType_name());
					}

					Integer spinnerInitPosition = 0;
					for (int i = 0; i < bizList.getItemCount(); i++) {
						if (memberList.getContent().getBizType().equals(bizList.getList().get(i).getType_name())) {
							spinnerInitPosition = i;
						}
					}

					ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, spinnerList);
					bizTypeSpinner.setAdapter(spinnerAdapter);
					spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					bizTypeSpinner.setSelection(spinnerInitPosition);

					bizTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
						public void onItemSelected(AdapterView<?> parent, View view,	int position, long id) {
							memberList.getContent().setBizType((String) bizTypeSpinner.getSelectedItem());
						}

						public void onNothingSelected(AdapterView<?> arg0) {
						}
					});
				} else {
					requestGson.alertToast(mContext, ApiCode.BIZTYPE +" 데이터 로딩 실패");
				}
			}
		};
		ThreadTask task = new ThreadTask((Activity)mContext, threadInterface);
		task.execute();
	}

	public void onClick(View v) {
		if(v.getId()==title.getId()){
			Intent intent=new Intent(this, MainIconView.class);
			intent.putExtra("flag", true);
			startActivity(intent);
		} else if(v.getId()==personalModifyDoneBt.getId() || v.getId()==businessModifyDoneBt.getId()){
			modifyInfo(ApiCode.UPDATEUSERINFORMATION);
		} else if(v.getId()==prevBt.getId()){
			finish();
		} else if(v.getId()==userPhoto.getId()){
			Intent intent=new Intent(this, PhotosActivity.class);
			intent.putExtra("userid", userid);
			intent.putExtra("code", ApiCode.MODIFYUSERPHOTO);
			startActivity(intent);
		} else {
			for(int i=0; i<bizPhotoResource.length; i++){
				if(v.getId()==bizPhoto[i].getId()){
					Intent intent=new Intent(this, PhotosActivity.class);
					intent.putExtra("userid", userid);
					intent.putExtra("code", ApiCode.MODIFYBIZPHOTO);
					startActivity(intent);
				}
			}
		}
	}
}
